package com.cxs.controller;

import com.cxs.common.lang.Const;
import com.cxs.controller.base.BaseController;
import com.cxs.entity.User;
import com.cxs.service.IUserService;
import com.cxs.utils.RedisUtil;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

@Slf4j
@RestController
public class AuthController {

    // Google的kaptcha自带的bean，用来生成验证码和验证码图片
    @Autowired
    private Producer producer;

    // 自定义Redis工具类
    @Autowired
    protected RedisUtil redisUtil;

    @Autowired
    IUserService userService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @GetMapping("/sys/userInfo")
    public User getUserInfo() {
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userService.getByUsername(username);
        user.setPassword("");
        return user;
    }

    /**
     * 图片验证码
     */
    @GetMapping("/captcha")
    public Map<Object, Object> captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成随机验证码
        String code = producer.createText();

        // 使用hutool工具生成32位随机验证码的key
        String key = UUID.randomUUID().toString();
        // 根据code生成验证码图片数据流
        BufferedImage image = producer.createImage(code);
        // 创建字节数组输出流实例
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // 把验证码图片写入字节数组输出流
        ImageIO.write(image, "jpg", outputStream);

        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        // 把验证码图片加密为base64格式
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        response.setHeader("Access-Control-Allow-Origin", "*");

        // 把验证码和验证码的key存储到redis中，120秒后失效
        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);
        log.info("验证码 -- {} - {}", key, code);
        // 将验证码的key作为token和加密后的验证码图片返回
        return MapUtil.builder()
                        .put("token", key)
                        .put("base64Img", base64Img)
                        .build();
    }

}
